package com.tutor.lzm.function.authenticate.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.squareup.picasso.Picasso;
import com.tutor.lzm.AppSession;
import com.tutor.lzm.R;
import com.tutor.lzm.app.CommonValue;
import com.tutor.lzm.app.Constant;
import com.tutor.lzm.fragment.BaseFragment;
import com.tutor.lzm.function.authenticate.act.CertificationTeacherAct;
import com.tutor.lzm.http.request.TeacherAuthenticationRequest;
import com.tutor.lzm.oss.UICallback;
import com.tutor.lzm.utils.ImageUtils;
import com.tutor.lzm.utils.SPKey;
import com.tutor.lzm.utils.UserOssUtils;
import com.tutor.syslib.Logs;
import com.tutor.syslib.impl.OneChoiceImpl;
import com.tutor.syslib.util.MessageTools;
import com.tutor.syslib.util.TextUtil;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by zzgpc on 2017-9-23.
 * 实名认证————学历认证
 */
public class EducationCertificationFragment extends BaseFragment {
    @BindView(R.id.tv_prompt_title_one)
    TextView tvPromptTitleOne;
    @BindView(R.id.ll_upload_one)
    LinearLayout llUploadOne;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.imageView)
    ImageView imageView;
    Unbinder unbinder;

    private UserOssUtils ossUtils;
    private TeacherAuthenticationRequest baseRequest;

    @Override
    public int getFragmentLayout() {
        return R.layout.fragment_education_certification;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);

        return rootView;
    }


    @Override
    protected void initView(Bundle bundle) {
        super.initView(bundle);
        baseRequest = (TeacherAuthenticationRequest) getArguments().getSerializable("data");
        ossUtils = new UserOssUtils(getContext(), null);
        ossUtils.initOssData();
        setNextClick();
        //显示学历照片
        String edu_cert_native = AppSession.getAppSPData(SPKey.edu_cert_native);
        if (TextUtil.isNull(edu_cert_native)) {
            String eduCertImageUrl = baseRequest.getEduCertImageUrl();
            if (!TextUtil.isNull(eduCertImageUrl)) {
                Picasso.with(getContext()).load(eduCertImageUrl).into(imageView);
            }
        } else {
            File file = new File(edu_cert_native);
            Picasso.with(getContext()).load(file).into(imageView);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ll_upload_one, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_upload_one:
                openCamera();
                break;
            case R.id.btn_next:

                if (TextUtil.isNull(baseRequest.getEduCertImageUrl()))
                    return;
                ((CertificationTeacherAct) getActivity()).saveAuthenticationRequest(baseRequest);
                ((CertificationTeacherAct) getActivity()).update("3");
                break;
        }
    }

    /**
     * 拍照弹出框
     */
    private void openCamera() {
        ArrayList<String> list = new ArrayList<>();
        list.add("相册");
        list.add("拍照");

        MessageTools.showOneChoiceDialog(getContext(), "请选择", list, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                switch (position) {
                    case 0:
                        // 从相册选取
                        ImageUtils.choicePicture(getActivity());

                        break;
                    case 1:
                        // 拍照
                        // 判断存储卡是否可以用，可用进行存储
                        if (ImageUtils.hasSdcard()) {
                            ImageUtils.takePicture(getActivity());
                        }
                        break;
                }
            }
        });

    }


    /**
     * 上传图片
     * 命名
     */
    private void upLoadImg(final String filePath) {
        String url;
        url = "eduCert/";
        url = url + AppSession.getInstance().getUserId() + ".png";
        mAct.showMyDialog("正在上传图片");
        ossUtils.asyncTaskUpload(url, filePath, getPutCallback(imageView, filePath, UserOssUtils.uploadUrl + url));


    }


    // 普通上传回调
    public UICallback<PutObjectRequest, PutObjectResult> getPutCallback(final ImageView view, final String imageName, final String url) {

        return new UICallback<PutObjectRequest, PutObjectResult>(ossUtils.UIDispatcher) {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Logs.d(tag, "UploadSuccess");
                AppSession.saveAppSessionData(SPKey.edu_cert_native, imageName);
                baseRequest.setEduCertImageUrl(url);
                AppSession.saveAppSessionData(SPKey.teacherAuthentication, baseRequest);
                addCallback(new Runnable() {
                    @Override
                    public void run() {
                        File file = new File(imageName);
                        Picasso.with(getContext()).load(file).into(view);
                        setNextClick();
                        mAct.closeDialog();
                    }
                }, null);

                super.onSuccess(request, result);
            }


            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {

                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Logs.e("ErrorCode", serviceException.getErrorCode());
                    Logs.e("RequestId", serviceException.getRequestId());
                    Logs.e("HostId", serviceException.getHostId());
                    Logs.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);

                addCallback(null, new Runnable() {

                    @Override
                    public void run() {
                        mAct.closeDialog();
                        MessageTools.showToast(getContext(), "图片上传失败！");
                    }
                });
                ossUtils.ossService.stopPutLoad();
                // mHandler.sendEmptyMessage( Constant.MSG_LOAD_ERROR );
                onFailure(request, clientExcepion, serviceException);
            }
        };
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == Constant.REQUEST_PICTURE) {
                // 相册
                Uri uri = data.getData();
                setPhotoImage(uri);
                //sendImage(uri);
            } else if (requestCode == Constant.REQUEST_CODE_BASE) {
                if (data != null && data.getData() != null) {
                    // 相机 并且获取到arg2
                    Uri uri = data.getData();
                    setPhotoImage(uri);
                    //   sendImage(uri);
                } else {
                    // 相机，获取不到intent数据
                    Uri uri = Uri.parse(CommonValue.openCameraUri);
                    setPhotoImage(uri);
                    //  sendImage(uri);
                }
            }


        }

    }


    /**
     * 解析uri是否存在
     *
     * @param uri
     */
    private void setPhotoImage(Uri uri) {


        String albumPath = ImageUtils.getPath(getContext(), uri);
        if (TextUtils.isEmpty(albumPath)) {
            MessageTools.showToast(getContext(), "获取照片失败，请重新拍照！");
            return;
        }

        File file = new File(albumPath);
        if (!file.exists()) {
            MessageTools.showToast(getContext(), "获取照片失败，请重新拍照！");
            return;

        }
        upLoadImg(albumPath);

    }


    /**
     * 是否能进行下一步
     */
    private boolean setNextClick() {
        if (TextUtil.isNull(baseRequest.getEduCertImageUrl()))
            return false;

        btnNext.setBackground(getResources().getDrawable(R.drawable.corner_bg_blue));
        btnNext.setClickable(true);
        return true;
    }

}
